import {
  creatPriceRule,
  updatePriceRule,
} from "@/services/rule/price_rule_api";
import { listLgExtrasDict } from "@/services/rule/speical_charges_api";
import {
  ModalForm,
  ProForm,
  ProFormDigit,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from "@ant-design/pro-components";
import dayjs from "dayjs";
import { message } from "antd";
import React, { useState, useEffect } from "react";
import { useIntl } from "umi";
import { PriceRuleVO } from "../../constants";

interface CreateModalProps {
  visible: boolean;
  values?: PriceRuleVO;
  onCancel: () => void;
  onSuccess: () => void;
}
interface SpecialChargeVo {
  name: string;
  code: string;
  value: string;
}

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};
const AddForm: React.FC<CreateModalProps> = ({
  visible,
  values,
  onCancel,
  onSuccess,
}) => {
  const [form] = ProForm.useForm<PriceRuleVO>();
  const intl = useIntl();

  // const [updateStatus, setUpdateStatus] = useState<boolean>(false);
  const [editStatus, setEditStatus] = useState<boolean>(false);

  const [specialCharges, setSpecialCharges] = useState<SpecialChargeVo[]>([]);

  useEffect(() => {

    if (visible) {
      if (values) {
        // console.log("rule:" + JSON.stringify(values));
        setEditStatus(true);
        if (values.ruleType === 0) {
          setIsSpecialChargeShow(false);
        } else {
          setIsSpecialChargeShow(true);
        }
        setCalculationRuleValue(values.calculationRule)
      }
      form.setFieldsValue(values || {});
    } else {
      setIsSpecialChargeShow(false);
    }
  }, [visible, values]);


  const initSpecialChargesData = async () => {
    try {
      // API调用逻辑
      const response = await listLgExtrasDict({});
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(
            intl.formatMessage({ id: "request.error.operating" })
          );
        } else {
          // throw new Error(response.msg);
          message.error(response.msg);
          return false;
        }
      }
      // let data:SpecialChargeVo[]=[];
      return response.data.map((item) => {
        return {
          label: item.lgExtrasCode + "[" + item.lgExtrasName + "]", // 其他字段转换...
          value: item.lgExtrasCode, // 假设需要重命名字段          
        }; // 显式类型断言
      });
    } catch (error) {
      message.error(intl.formatMessage({ id: "request.error.retry" }));
      return false;
    }
  };

  const handleSubmit = async (formValues: PriceRuleVO) => {
    //  console.log("customer1:" + JSON.stringify(values));
    if (formValues.ruleType === 0) {
      formValues.feeItemCode = 'Basic_Fee';
    }
    if (values?.id) {
      formValues.id = values?.id;
      // formValues.customerId = values?.customerId;
      // formValues.customerCode = values?.customerCode;
      return await handleUpdateData(formValues);
    }
    try {
      // API调用逻辑
      const response = await creatPriceRule(formValues);

      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(
            intl.formatMessage({ id: "request.error.operating" })
          );
        } else {
          // throw new Error(response.msg);
          message.error(response.msg);
          return false;
        }
      }
      message.success(intl.formatMessage({ id: "request.success.operating" }));
      onSuccess();
      form.resetFields();
      return true;
    } catch (error) {
      message.error(intl.formatMessage({ id: "request.error.retry" }));
      return false;
    }
  };

  const handleUpdateData = async (updateData: PriceRuleVO) => {
    try {
      // API调用逻辑

      const response = await updatePriceRule(updateData.id, updateData);

      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(
            intl.formatMessage({ id: "request.error.operating" })
          );
        } else {
          // throw new Error(response.msg);
          message.error(response.msg);
          return false;
        }
      }
      message.success(intl.formatMessage({ id: "request.success.operating" }));
      onSuccess();
      form.resetFields();
      return true;
    } catch (error) {
      message.error(intl.formatMessage({ id: "request.error.retry" }));
      return false;
    }
  };

  const handleValuesChange = (changedValues, allValues) => {
    // changedValues 是发生变化的字段
    // allValues 是表单当前所有的值
    // console.log(changedValues);
  };

  const [isSpecialChargeShow, setIsSpecialChargeShow] = useState(false);

  // 监听 ruleType 变化
  const handleRuleTypeChange = (value: any) => {
    if (value === 0) {
      // 当选择基础收费项时：
      // 1. 设置默认值（假设默认值为 "DEFAULT_CODE"，根据实际需求替换）
      form.setFieldsValue({ feeItemCode: "Basic_Fee" });
      // 2. 禁用 feeItemCode 字段
      // setIsFeeItemCodeDisabled(true);
      setIsSpecialChargeShow(false);
    } else {
      // 当选择特殊收费项时：
      // 1. 清空默认值
      form.setFieldsValue({ feeItemCode: '' });

      setIsSpecialChargeShow(true);
    }
  };

  const [calculationRuleValue, setCalculationRuleValue] = useState<string>('');
  // 监听 calculationRule 变化
  const handleCalculationRuleChange = (value:string) => {
    setCalculationRuleValue(value);
  };

  const closeModel = () => {
    form.resetFields;
    setCalculationRuleValue('');
    setIsSpecialChargeShow(false);
    onCancel();
  }

  const checkPrice = (_: any, value: any) => {
    console.log("number:" + value);
    if (value && parseInt(value, 10) <= 0) {
      return Promise.reject(new Error("Must be greater than 0"));
    }
    return Promise.resolve();
  };


  return (
    <ModalForm<PriceRuleVO>
      title={
        values?.id
          ? intl.formatMessage({ id: "pages.edit" })
          : intl.formatMessage({ id: "pages.create" })
      }
      width="40%"
      form={form}
      open={visible}
      onOpenChange={(visible) => !visible && closeModel()}
      onFinish={handleSubmit}
      onValuesChange={handleValuesChange} // 监听值变化
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
      }}
      submitter={{
        searchConfig: {
          submitText: intl.formatMessage({ id: "pages.button.submit" }),
          resetText: intl.formatMessage({ id: "pages.button.cancel" }),
        },
      }}
      layout="horizontal"
      {...formItemLayout}
    >
      {/* 单列布局 - 移除了所有 ProForm.Group */}
      {/* <ProForm.Group></ProForm.Group>  */}
      {/* 单列布局 */}
      <ProFormText
        name="ruleName"
        colProps={{ md: 12, xl: 8 }}
        label={intl.formatMessage({
          id: "pages.price.ruleName",
          defaultMessage: "Rule Name",
        })}
        placeholder={intl.formatMessage({ id: "pages.price.ruleName" })}
        rules={[
          {
            required: true,
            message: intl.formatMessage({ id: "pages.price.ruleName" }),
          },
        ]}
      />

      <ProFormText
        name="ruleCode"
        disabled={editStatus}
        colProps={{ md: 12, xl: 8 }}
        label={intl.formatMessage({
          id: "pages.price.ruleCode",
          defaultMessage: "Rule Code",
        })}
        placeholder={intl.formatMessage({ id: "pages.price.ruleCode" })}
        rules={[
          {
            required: true,
            message: intl.formatMessage({ id: "pages.price.ruleCode" }),
          },
        ]}
      />
      <ProFormSelect
        name="ruleType"
        colProps={{ md: 12, xl: 8 }}
        label={intl.formatMessage({
          id: "pages.price.ruleType",
          defaultMessage: "Rule Type",
        })}
        placeholder={intl.formatMessage({ id: "pages.price.ruleType" })}
        rules={[
          {
            required: true,
            message: intl.formatMessage({ id: "pages.price.ruleType" }),
          },
        ]}
        options={[
          {
            value: 0,
            label: intl.formatMessage({
              id: "pages.price.ruleType.base",
              defaultMessage: "Base Fee",
            }),
          },
          {
            value: 1,
            label: intl.formatMessage({
              id: "pages.price.ruleType.special",
              defaultMessage: "Special Fee",
            }),
          },
        ]}
        onChange={handleRuleTypeChange} // 监听变化
      />

      {isSpecialChargeShow && (
        <ProFormSelect
          name="feeItemCode"
          label={intl.formatMessage({
            id: "pages.price.feeItemCode",
            defaultMessage: "Fee Item Code",
          })}
          request={initSpecialChargesData}
          placeholder={intl.formatMessage({ id: "pages.price.feeItemCode" })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: "pages.price.feeItemCode" }),
            },
          ]}
        />
      )}

      <ProFormSelect
        name="calculationRule"
        label={intl.formatMessage({
          id: "pages.price.calculationRule",
          defaultMessage: "Calculation Rule",
        })}
        placeholder={intl.formatMessage({ id: "pages.price.calculationRule" })}
        rules={[
          {
            required: true,
            message: intl.formatMessage({ id: "pages.price.calculationRule" }),
          },
        ]}
        options={[
          {
            value: "Fixed_Price",
            label: intl.formatMessage({
              id: "pages.price.calcType.fixedPrice",
              defaultMessage: "Fixed Price",
            }),
          },
          {
            value: "Floating_Rate",
            label: intl.formatMessage({
              id: "pages.price.calcType.floatingRate",
              defaultMessage: "Floating Rate",
            }),
          },
          {
            value: "Fixed_Additional",
            label: intl.formatMessage({
              id: "pages.price.calcType.fixedAdditional",
              defaultMessage: "Fixed Additional",
            }),
          },
          {
            value: "Segmented",
            label: intl.formatMessage({
              id: "pages.price.calcType.Segmented",
              defaultMessage: "Segmented",
            }),
          },
        ]}
        onChange={handleCalculationRuleChange} // 监听变化
      />

      {calculationRuleValue === "Floating_Rate" ? (
        // 浮动费率模式：百分比输入框
        <ProFormText
          name="ruleValue"
          label={intl.formatMessage({
            id: "pages.price.ruleValue",
            defaultMessage: "Rule Value",
          })}
          placeholder={intl.formatMessage({ id: "pages.price.ruleValue" })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: "pages.price.ruleValue" }),
            },
            {
              pattern: /^\d*\.?\d+$/, // 只允许数字
              message: "Only positive number are allowed",
            },
            { validator: checkPrice },
          ]}
          fieldProps={{
            addonAfter: "%", // 添加 % 符号
            formatter: (value) => `${value}%`, // 显示时添加 %
            parser: (value) => value.replace("%", ""), // 解析时去掉 %
          }}
        />
      ) : calculationRuleValue === "Segmented" ? (
        // 其他模式：普通数字输入框
        <ProFormTextArea
          name="ruleExtendValue"
          label={intl.formatMessage({
            id: "pages.price.ruleExtendValue",
            defaultMessage: "Extend Value",
          })}
          // placeholder={intl.formatMessage({ id: "pages.price.ruleExtendValue" })}
          placeholder={`[
  {
    "rangeBegin": 0,
    "rangeEnd": 500,
    "calculationRule": "rate",
    "ruleValue": 1.2
  },
  {
    "rangeBegin": 500,
    "rangeEnd": 1000,
    "calculationRule": "rate",
    "ruleValue": 1.1
  },
  {
    "rangeBegin": 1000,
    "calculationRule": "add",
    "ruleValue": 100
  }
]`}
          fieldProps={{
            style: { whiteSpace: "pre-wrap" }, // 保留换行和空格
            autoSize: { minRows: 3 }, // 自适应高度
          }}
          extra={
            <div
              style={{
                whiteSpace: "pre-line", // 保留换行但合并空格
                lineHeight: 1.6, // 增加行高
                color: "rgba(0, 0, 0, 0.45)", // Ant Design 默认提示色
                fontSize: 14, // 适当字体大小
              }}
            >
              {intl.formatMessage({
                id: "pages.price.range.description",
              })}
            </div>
          }
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: "pages.price.ruleExtendValue",
              }),
            },
          ]}
        />
      ) : (
        // 其他模式：普通数字输入框
        <ProFormText
          name="ruleValue"
          label={intl.formatMessage({
            id: "pages.price.ruleValue",
            defaultMessage: "Rule Value",
          })}
          placeholder={intl.formatMessage({ id: "pages.price.ruleValue" })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: "pages.price.ruleValue" }),
            },
            {
              pattern: /^\d*\.?\d+$/, // 只允许数字
              message: "Only positive number are allowed",
            },
            { validator: checkPrice },
          ]}
        />
      )}

      <ProFormTextArea
        name="description"
        label={intl.formatMessage({
          id: "pages.price.desc",
          defaultMessage: "Rule Desc",
        })}
        placeholder={intl.formatMessage({ id: "pages.price.desc" })}
      />
    </ModalForm>
  );
};

export default AddForm;
